/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.CustomerIOTRPortal;

import helper.tx.Helper_LineItem;
import session.TX.*;
import entity.tx.*;
import Web_Helper.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.primefaces.event.RowEditEvent;
import session.CM.PortalManagementSB;

/**
 *
 * @author Randall Chia
 */
@ManagedBean(name = "cartBean")
@SessionScoped
public class ShoppingCartMB {
    
    @EJB
    private PortalManagementSB portalManagementSB;

    @EJB
    private TransactionManagerSBRemote transactionManager;
    
    @EJB
    private ULPSBRemote loyaltypointsManager;
    
    @EJB
    private UsersSBRemote userManager;
    
    @EJB
    private ShoppingCartSBRemote cartManager;

    //Used to hold the Groupon which the customer is currently looking at
    private GroupBuyingItem current_viewed_groupon;
    
    private List<Helper_LineItem> cart;
    private List<Helper_LineItem> addStuff = new ArrayList<Helper_LineItem>();
    private String purchaseStatusMSG = "DEFAULT";
    
    private String customerEmail;
    private Long customerID;

    /** Creates a new instance of ShoppingCartMB */
    public ShoppingCartMB() {
        addStuff.add(new Helper_LineItem(632, "Big and Tasty Meal", 1, 6.50, "Mc'Donalds", 2, "Clementi"));  
        addStuff.add(new Helper_LineItem(633, "Zinger Burger", 1, 3.50, "KFC", 3, "VivoCity"));
        
        try{
        customerEmail = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString();
        customerID = (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("accountId");
        }
        catch(NullPointerException e){}

        
    }
    
    
    
    
    
    
    public void printCart(){
        System.out.println(">>> cartBean printing the shopping cart of user: " + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString());
        for(Helper_LineItem  o : getCartManager().getCart()){
            System.out.println("*************** " + o);
        }
    }
    
    
    
    
    
    
    public void updateListenAction(RowEditEvent event){
        getCartManager().setCart(cart);
    }
    

    //Retrieve the cart items
    public List<Helper_LineItem> getItems() {
        if (cart == null) {
            cart = getCartManager().getCart();
        }
        return cart;
    }//------------------------------------------------------------------------------------------

    //Delete an item from the cart
    public void removeFromCart(Helper_LineItem item) {
        cart.remove(item);
        getCartManager().setCart(cart);
        //getCartManager().cart_remove(item);
    }//------------------------------------------------------------------------------------------

    //Add one or more Line Items into the cart
    public void addItems() {
        cart = null;
        getCartManager().cart_addMultipleItems(addStuff);
    }//------------------------------------------------------------------------------------------

    //clear the cart items
    public void emptyCart() {
        cart = null;
        getCartManager().cart_removeAllItems();
    }//------------------------------------------------------------------------------------------

    //get the subtotal.
    public double getSubtotal() {
        return getCartManager().getSubtotal();
    }//------------------------------------------------------------------------------------------

    //Perform validation of a payment
    public void validatePayment() {

        boolean validationResult = false;
        try {
            validationResult = Helper_PaymentValidator.validatePayment();
        } catch (IOException e) {
        }

        if (validationResult == true) {
            System.out.println("Payment Validation: SUCCESS");
   
            this.doTransactionLog();
            this.emptyCart();
            //purchaseStatusMSG = "YOUR SHOPPING CART IS CHECKED OUT!<br/>THANK YOU FOR SHOPPING AT FOODSAGE!";
            
        }//end THEN block
        else {
            System.out.println("Payment Validation: FAIL");
            purchaseStatusMSG = "Error: Your Payment has failed Validation";
        }

    }//------------------------------------------------------------------------------------------

    public void doTransactionLog() {
        try{
            if(cart==null){}
        }catch(NullPointerException e){
            purchaseStatusMSG = "Nothing to display";
            return;
        }

        
         customerEmail = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString();
         customerID = Long.valueOf(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("accountId").toString());
        
        
        //Find the customer
        List<Users> userList = userManager.getAllUser();
        
        Integer customer_age = 0;
        String customer_country = " ";
        
        for(Users o: userList){
            if(o.getId().equals(customerID)){

                Calendar cal1 = Calendar.getInstance();
                int thisYear = cal1.get(Calendar.YEAR);
                
                Calendar cal2 = Calendar.getInstance();
                cal2.setTime(o.getBirthDate());
                int customerBirthYear = cal2.get(Calendar.YEAR);
                
                customer_age = thisYear - customerBirthYear;                      
                customer_country = o.getCountry().getCountry();
            }
        }

        System.out.println("Customer " + customerEmail + " checked out their shopping cart");

        Calendar transaction_timestamp = Calendar.getInstance();
        
        double subtotal = this.getSubtotal();
        Integer loyaltyPointsAwarded = loyaltypointsManager.calculateLoyaltyPoints(transaction_timestamp.getTime(), customerEmail, subtotal);

        //generate the list of purchase items to put into the transaction entry
        List<PurchasedItem> purchasedItemList = new ArrayList<PurchasedItem>();

        for (Helper_LineItem item : cart) {
            PurchasedItem itemEntity = transactionManager.createPurchasedItem_Regular(
                    transaction_timestamp,
                    customerEmail,
                    item.getSeller(),
                    item.getItem_name(),
                    item.getItem_ID(),
                    item.getItem_quantity() * item.getItem_price(),
                    customer_country,
                    customer_age,
                    item.getItem_outletID(), item.getItem_quantity(), item.getItem_outletName(), item.getItem_stakeholderId(), item.getItem_customerId());


            purchasedItemList.add(itemEntity);
        }//end for
        
        double total=0;
        
        SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MMM-yyyy");
        Date tempDate = transaction_timestamp.getTime();
        
        String emailMsg= "E Receipt for " + customerEmail + " \n\n" + "Transaction Date: " + dateformatter.format(tempDate) + " \n\n" + "|    N.o    |            Item           |           Restaurant           |             Branch             |           Amount             |\n";
        emailMsg = emailMsg + "-------------------------------------------------------------------------------------------------------------------------------------------------------\n";
        for(int x=0; x<purchasedItemList.size(); x++){
            PurchasedItem_Regular item = (PurchasedItem_Regular)purchasedItemList.get(x);
            emailMsg = emailMsg + x + "               " + item.getItem_name() + "                 " + item.getSeller() + "                 " + item.getOutlet_name() + "               SGD $" + item.getSubtotal()  + " \n";
            emailMsg = emailMsg + "-------------------------------------------------------------------------------------------------------------------------------------------------------\n";
            total = total + item.getSubtotal();
        }
        emailMsg = emailMsg + "\n\nSubtotal: SGD $" + total;
        
        
        
        
        //MAIL START

        String emailMessage = emailMsg;


        String senderEmail = portalManagementSB.getEmailFrom();
        String senderPassword = portalManagementSB.getEmailPassword();
        EmailSender emailsender = new EmailSender(senderEmail, senderPassword);
        String[] recepients = {customerEmail};

        try {
            emailsender.postMail(recepients, "FoodSage Shopping Cart Checkout", emailMessage, senderEmail);
        } catch (javax.mail.MessagingException e) {
        }

        //MAIL END
        
        
        
        
        
        
        
        
        

        transactionManager.createTransactionEntry(
                transaction_timestamp,
                customerEmail,
                loyaltyPointsAwarded,
                subtotal,
                purchasedItemList);
        
        
        
            //Start compose status message for front end 
            //--------------------------------------------------------------
            NumberFormat formatter = new DecimalFormat("#0.00");
            purchaseStatusMSG =
                      "<h4>Customer: </h4>" + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString() + "<br/>"
                    + "<h4>Timestamp: </h4>" + transaction_timestamp.getTime() + "<br/><br/>"
                    + "<h4>Items: </h4><br/>"
                    + "<table border='0' cellspacing='6'>"
                    + "<col width='200' /><col width='40' /><col width='40' /><col width='200' /><col width='300' />"
                    + "<tr> <td><h5>Item</h5></td>   <td><h5>Quantity</h5></td>   <td><h5>Price</h5></td>   <td><h5>Seller</h5></td>   <td><h5>Outlet</h5></td> </tr>"
                    ;        
            for(Helper_LineItem item : cart){
                purchaseStatusMSG = purchaseStatusMSG +
                        "<tr>"
                        + "<td>" + item.getItem_name() + "</td>"        + "<td>" + item.getItem_quantity() + "</td>"        + "<td>&#36;" + formatter.format(item.getItem_price()) + "</td>"        + "<td>" + item.getSeller() + "</td>"        + "<td>" + item.getItem_outletName() + "</td>"
                        +"</tr>";
            }

            purchaseStatusMSG = purchaseStatusMSG + "</table>";
            //End compose status message
            //--------------------------------------------------------------
        
        
    }//------------------------------------------------------------------------------------------

    

    public List<PurchasedItem_Regular> customerGetPurchases(){    
        String customerEmail = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString();  
        return transactionManager.retrievePurchasedItemRegular(customerEmail, null, false);
    } 
    
    
    
    
    
    
    


    /**
     * @return the cart
     */
    public List<Helper_LineItem> getCart() {
        return cart;
    }

    /**
     * @param cart the cart to set
     */
    public void setCart(List<Helper_LineItem> cart) {
        this.cart = cart;
    }

    /**
     * @return the addStuff
     */
    public List<Helper_LineItem> getAddStuff() {
        return addStuff;
    }

    /**
     * @param addStuff the addStuff to set
     */
    public void setAddStuff(List<Helper_LineItem> addStuff) {
        this.addStuff = addStuff;
    }

    /**
     * @return the purchaseStatusMSG
     */
    public String getPurchaseStatusMSG() {
        return purchaseStatusMSG;
    }

    /**
     * @param purchaseStatusMSG the purchaseStatusMSG to set
     */
    public void setPurchaseStatusMSG(String purchaseStatusMSG) {
        this.purchaseStatusMSG = purchaseStatusMSG;
    }

    /**
     * @return the cartManager
     */
    public ShoppingCartSBRemote getCartManager() {
        return cartManager;
    }

    /**
     * @param cartManager the cartManager to set
     */
    public void setCartManager(ShoppingCartSBRemote cartManager) {
        this.cartManager = cartManager;
    }

    /**
     * @return the customerEmail
     */
    public String getCustomerEmail() {
        return customerEmail;
    }

    /**
     * @param customerEmail the customerEmail to set
     */
    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    /**
     * @return the customerID
     */
    public Long getCustomerID() {
        return customerID;
    }

    /**
     * @param customerID the customerID to set
     */
    public void setCustomerID(Long customerID) {
        this.customerID = customerID;
    }

    /**
     * @return the current_viewed_groupon
     */
    public GroupBuyingItem getCurrent_viewed_groupon() {
        return current_viewed_groupon;
    }

    /**
     * @param current_viewed_groupon the current_viewed_groupon to set
     */
    public void setCurrent_viewed_groupon(GroupBuyingItem current_viewed_groupon) {
        this.current_viewed_groupon = current_viewed_groupon;
    }
    
    
    
    
}


